const Koa = require('koa')
const app = new Koa()

const Router = require('koa-router')
const router = new Router()

const koaBody = require('koa-body')
app.use(koaBody.default())

const cors = require('koa2-cors')
app.use(cors())

const mongoose = require('mongoose')
//将Model导入
const Comment = require('./models/comment')
const User = require('./models/User')
//用户评论增加
router.post("/addcomment",async(ctx,next) =>{
	await next()
	let commenttext = ctx.request.body["commenttext"]
	let value = ctx.request.body["value"]
	if (commenttext == undefined || commenttext == '') {
		ctx.body = {msg:"评论内容不能为空",err:""}
		return
	}
	if (value <= 0 ){
		ctx.body = {msg:"评论星级不能为空",err:""}
		return
	}
	let result = await new Comment({
			commenttext,
			value
		}).save().then(() => {
			return {msg:"评论保存成功",err:""}
		}).catch(err => {
			return {msg:"评论保存不成功",err:err}
		})
		ctx.body = result
})

//用户注册功能
router.post("/regist", async (ctx, next) => {
	await next()
	let uname = ctx.request.body["uname"]
	let utel = ctx.request.body["utel"]
	let upassword = ctx.request.body["upassword"]
	if (uname == undefined || uname == '') {
		ctx.body = {msg:"用户名称不能为空",err:""}
		return
	}
	if (utel == undefined || utel == '') {
		ctx.body = {msg:"用户电话不能为空",err:""}
		return
	}
	if (upassword == undefined || upassword == '') {
		ctx.body = {msg:"用户密码不能为空",err:""}
		return
	}
	// 注册本质，存
	let result = await new User({
		uname,
		utel,
		upassword
	}).save().then(() => {
		return {msg:"用户保存成功",err:""}
	}).catch(err => {
		return {msg:"用户保存不成功",err:""}
	})
    ctx.body = result
})
app.use(router.routes())
app.listen(3030, err => {
	if (err) console.error(err)
	console.log('3030已开启')
	mongoose.connect('mongodb://127.0.0.1:27017/hotel')
})